package cn.xs.user.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import cn.xs.core.util.IDUtils;
import cn.xs.goods.entity.Category;
import cn.xs.goods.entity.Good;
import cn.xs.goods.service.CategoryService;
import cn.xs.goods.service.GoodService;
import cn.xs.order.entity.Order;
import cn.xs.order.service.OrderService;
import cn.xs.user.entity.Admin;
import cn.xs.user.service.AdminService;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 管理员控制器
 * 		负责网站后台全部业务
 * @author xs
 *
 */
public class AdminAction extends ActionSupport{
	
	@Resource
	private AdminService adminService;
	@Resource
	private CategoryService categoryService;
	@Resource
	private GoodService goodService;
	@Resource
	private OrderService orderService;
	
	
	private Admin admin;
	private List<Category> categoryList;
	private List<Good> goodList;
	private List<Order> orderList;
	private Category pcategory;	//父分类
	private Category category;
	private Good good;
	private Order order;
	
	private File goodImg;
	private String goodImgFileName;
	private String goodImgContentType; //
	
	/**
	 * 跳转到分类管理页面
	 * @return
	 */
	public String toCategoryUI(){
		categoryList = categoryService.findParentsCategory();
		return "categoryUI";
	}
	
	/**
	 * 跳转到新增分类页面
	 */
	public String toAddCategoryUI(){
		if(pcategory!=null && pcategory.getId()!=null){
			pcategory = categoryService.find(pcategory.getId());
		}
		return "addCategoryUI";
	}
	
	/**
	 * 跳转到商品管理页面
	 * @return
	 */
	public String toGoodUI(){
		return "goodUI";
	}
	/**
	 * 跳转到增加商品页面
	 * @return
	 */
	public String toAddGoodUI(){
		return "addgoodUI";
	}
	
	/**
	 * 跳转到商品详细页面
	 * @return
	 */
	public String toDetailUI(){
		if(good!=null && good.getId()!=null){
			good = goodService.find(good.getId());
			
			
		}
		return "detailUI";
	}
	/**
	 * 跳转到管理员登录页面
	 * @return
	 */
	public String tologinUI(){
		return "loginUI";
	}
	
	
	/**
	 * 登录方法,成功后跳转到分类管理去
	 * @return
	 */
	public String login(){
		if(admin!=null){
			Admin adminInfo = adminService.login(admin.getAccount(),admin.getPassword());
			if(adminInfo!=null){
				//登录成功
				ServletActionContext.getRequest().getSession().setAttribute("ADMIN_INFO", adminInfo);
				//重定向action到分类页面去
				return "categoryUIr";
			}
		}
		//带提示过去
		ServletActionContext.getRequest().setAttribute("message", "帐号或密码错误,请重新登录!");
		return "loginUI";
	}
	
	/**
	 * 保存新增的分类
	 * @return
	 */
	public String addCategory(){
		if(category!=null){
			category.setId(IDUtils.getRandomID());
			category.setParent_id(pcategory.getId());
			categoryService.save(category);
		}
		return "categoryUIr";
	}
	
	/**
	 * 保存新增的商品
	 * @return
	 */
	public String addGood(){
		if(good!=null && category!=null){
			good.setCategory_id(category.getId());
			good.setId(UUID.randomUUID().toString().replaceAll("-", ""));
			good.setImg(saveGoodImg());	//设置图片
			goodService.save(good);
		}
		return "goodUI";
	}
	
	/**
	 * 删除子分类
	 * @return
	 */
	public String deleteCategory(){
		if(category!=null){
			categoryService.delete(category.getId());
		}
		return "categoryUIr";
	}
	
	/**
	 * 异步获取二级分类
	 */
	public void ajaxgetCategory(){
		if(pcategory!=null){
			try {
				//获取二级分类
				categoryList = categoryService.findCategorysByPid(pcategory.getId());
				JSONObject results = new JSONObject();
				results.put("msg", "success");
				results.put("categorylist", categoryList);
				
				HttpServletResponse response = ServletActionContext.getResponse();
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(results.toString());
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	}
	
	/**
	 * 异步获取商品
	 */
	public void ajaxgetGood(){
		if(category!=null){
			try {
				//获取二级分类
				goodList = goodService.findAllByCategory(category.getId());
				
				JSONObject results = new JSONObject();
				results.put("msg", "success");
				results.put("goodlist", goodList);
				
				HttpServletResponse response = ServletActionContext.getResponse();
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(results.toString());
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	}
	
	/**
	 * 保存商品修改
	 * @return
	 */
	public String doModify(){
		if(good!=null){
			if(goodImg!=null){
				good.setImg(saveGoodImg());
			}
			goodService.update(good);
		}
		return "goodUI";
	}
	
	/**
	 * 退出
	 * @return
	 */
	public String quit(){
		//销毁session
		ServletActionContext.getRequest().getSession().invalidate();
		return "loginUI";
	}
	
	/**
	 * 跳转到订单管理页面
	 * @return
	 */
	public String toOrderUI(){
		try {
			if(order!=null){
				String status = new String(order.getStatus().getBytes("iso-8859-1"),"utf-8");
				orderList = orderService.findAllByStatus(status);
			}else{
				orderList = orderService.findAll();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "orderUI";
	}
	
	/**
	 * 挑战到订单详细页面去
	 * @return
	 */
	public String toOrderDetailUI(){
		if(order!=null && order.getId() != null){
			order = orderService.find(order.getId());
		}
		return "orderDetailUI";
	}
	
	/**
	 * 发货
	 * 		订单状态改为发货
	 */
	public String doSend(){
		if(order!=null && order.getId()!=null){
			orderService.setOrderStatus(order.getId(), Order.order_delivered);
		}
		return "orderUIr";
	}
	
	/**
	 * 保存图书图片,并且返回路径
	 * @return
	 */
	private String saveGoodImg(){
		if(goodImg!=null){
			try {
				//1 获取服务器本地项目保存路径 如 c:\tomcat\webapps\itcastTax\ upload\ user
				String prePath = ServletActionContext.getServletContext()
						.getRealPath("/img/goods");
				String fileName = UUID.randomUUID().toString().replace("-",
						"")
						+ goodImgFileName.substring(goodImgFileName
								.lastIndexOf("."));
				//2 复制当前图片到服务器项目目录/img/goods里去
				FileUtils.copyFile(goodImg, new File(prePath, fileName));
				//3 返回路径
				return fileName;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	
	public Admin getAdmin() {
		return admin;
	}
	public void setAdmin(Admin admin) {
		this.admin = admin;
	}
	public List<Category> getCategoryList() {
		return categoryList;
	}
	public void setCategoryList(List<Category> categoryList) {
		this.categoryList = categoryList;
	}
	public Category getCategory() {
		return category;
	}
	public void setCategory(Category category) {
		this.category = category;
	}
	public Category getPcategory() {
		return pcategory;
	}
	public void setPcategory(Category pcategory) {
		this.pcategory = pcategory;
	}
	public List<Good> getGoodList() {
		return goodList;
	}
	public void setGoodList(List<Good> goodList) {
		this.goodList = goodList;
	}
	public Good getGood() {
		return good;
	}
	public void setGood(Good good) {
		this.good = good;
	}
	public File getGoodImg() {
		return goodImg;
	}
	public void setGoodImg(File goodImg) {
		this.goodImg = goodImg;
	}
	public String getGoodImgFileName() {
		return goodImgFileName;
	}
	public void setGoodImgFileName(String goodImgFileName) {
		this.goodImgFileName = goodImgFileName;
	}
	public String getGoodImgContentType() {
		return goodImgContentType;
	}
	public void setGoodImgContentType(String goodImgContentType) {
		this.goodImgContentType = goodImgContentType;
	}
	public List<Order> getOrderList() {
		return orderList;
	}
	public void setOrderList(List<Order> orderList) {
		this.orderList = orderList;
	}
	public Order getOrder() {
		return order;
	}
	public void setOrder(Order order) {
		this.order = order;
	}
	
}
